package com.memoryangelapplication.services;

import java.security.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import com.memoryangelapplication.AlertMessageActivity;
import com.memoryangelapplication.global.Event_pass;
import com.memoryangelapplication.model.EventObj;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
import android.widget.Toast;

public class EventAlarm extends WakefulBroadcastReceiver {

	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "memoryangel.db";
	private String MEM_EVENT = "table_events";
    int timeout = 30;
	private Context passcontext;

	ArrayList<EventObj> lst = new ArrayList<EventObj>();

	private final String REMINDER_BUNDLE = "MyReminderBundle";

	public EventAlarm() {
	}

	public EventAlarm(Context context, Bundle extras, int timeoutInSeconds) {
	
		passcontext = context;
		int xx= timeoutInSeconds;
		
		AlarmManager alarmMgr = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, EventAlarm.class);
		intent.putExtra(REMINDER_BUNDLE, extras);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
				intent, PendingIntent.FLAG_UPDATE_CURRENT);
		Calendar time = Calendar.getInstance();
		time.setTimeInMillis(System.currentTimeMillis());
		time.add(Calendar.SECOND, xx);

		/*
		 * alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
		 * time.getTimeInMillis(), 1000*1, pendingIntent);
		 */
		alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
				pendingIntent);

	}

	@Override
	public void onReceive(Context context, Intent intent) {
		//Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();

		String nowunixtime = getAddDateTimeString().toString();

		mydb = context.openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		ContentValues newrowfDealer = new ContentValues();
		Cursor fdealerrows = null;

		try {
			/*fdealerrows = mydb.query(MEM_EVENT, null,
					"event_active = '0' AND event_alam_time < '" + nowunixtime
							+ "' AND event_status != '3'", null, null, null, null);*/
			String query = "SELECT * FROM table_events WHERE event_active !='3' AND event_alam_time < '"
					+ nowunixtime + "' AND event_active = '0' ORDER BY event_alam_time ASC LIMIT 1";
			fdealerrows = mydb.rawQuery(query, null);
			
			
			
		} catch (Exception e) {
		}

		if (fdealerrows != null) {
			if (fdealerrows.getCount() > 0) {
				while (fdealerrows.moveToNext()) {
					Log.e("Triger Alert ", "ALERT XXX :" + fdealerrows.getString(0));
					lst.add(new EventObj(fdealerrows.getString(3), fdealerrows
							.getString(4), fdealerrows.getString(2),
							fdealerrows.getString(7), fdealerrows.getString(4),
							fdealerrows.getString(5), fdealerrows.getString(6),
							fdealerrows.getString(7), fdealerrows.getString(9),
							fdealerrows.getString(8), fdealerrows.getString(6),
							fdealerrows.getString(16), fdealerrows
									.getString(17), fdealerrows.getString(18), fdealerrows.getString(1)));
					fdealerrows.moveToNext();
				}

			} else {

			}
		}
		mydb.close();

	

		if (!lst.isEmpty()) {
			EventObj mth = (EventObj) lst.get(0);

			Event_pass.setData_pass(lst);

			if (mth != null) {
				Intent i2 = new Intent(context, AlertMessageActivity.class);
				i2.putExtra("event_log_id", mth.getEvent_event_log_id());
				i2.putExtra("event_id", mth.getEvent_time_stamp());
				i2.putExtra("event_title", mth.getEvent_title());
				i2.putExtra("event_date", mth.getEvent_date());
				i2.putExtra("event_time", mth.getEvent_time());
				i2.putExtra("event_description", mth.getEvent_description());
				i2.putExtra("event_eventremindertime", mth.getEvent_eventremindertime());
				i2.putExtra("event_eventremindernumber", mth.getEvent_eventremindernumber());
				i2.putExtra("event_eventwaittime", mth.getEvent_eventwaittime());
				i2.putExtra("nxt_incr", "1");
				i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(i2);
			}
		}

	}

	private void runOnUiThread(Runnable runnable) {
		// TODO Auto-generated method stub

	}

	public class AlertUI extends AsyncTask<String, Void, String> {
		private Context asynccontext;
		public AlertUI(Context passContext) {
			super();
			asynccontext = passContext;
		}

		@Override
		protected String doInBackground(String... urls) {

			for (int i = 0; i < lst.size(); i++) {
				EventObj mth = (EventObj) lst.get(i);

				Intent i2 = new Intent(asynccontext, AlertMessageActivity.class);

				i2.putExtra("event_title", mth.getEvent_title());
				i2.putExtra("event_date", mth.getEvent_date());
				i2.putExtra("event_time", mth.getEvent_time());
				i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				asynccontext.startActivity(i2);

			}
			return null;
		}

	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyyMMddHHmm");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	private String getCurrentTimeString() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("yyyy-MM-dd");
		String date_to_string = ddMMMyyFormat.format(c.getTime());
		return date_to_string;
	}

	private String getCurrentTimeStringTime() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("hh:mm a");
		String date_to_string = ddMMMyyFormat.format(c.getTime());
		return date_to_string;
	}

}
